package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.exception.orderException;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderDTO;
import com.itheima.service.OrderService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@Api(tags = "预约管理")
@RequiredArgsConstructor
public class OrderController {
    private final OrderService orderService;
    private final RedisTemplate redisTemplate;
    @PostMapping("/order/findById")
    public Result findById(Integer id){
        log.info("查询id为{}的预约信息",id);
        Result result = new Result();
        try {

            result.setData(orderService.findById(id));
            result.setFlag(true);
            result.setMessage(MessageConstant.QUERY_ORDER_SUCCESS);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setFlag(false);
        }
        return result;
    }

    @PostMapping("/order/submitOrder")
    public Result submitOrder(@RequestBody OrderDTO order){
        Result result = new Result();
        try {
            orderService.submitOrder(order);
            result.setData(order.getId());
            result.setFlag(true);
            result.setMessage(MessageConstant.ORDER_SUCCESS);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping("/validatecode/send4Order")
    public Result send4Order(String telephone){
        Result result = new Result();
        try {
            Integer validateCode= (int)((Math.random()*9+1)*100000);
            log.info("验证码：{}",validateCode);
            redisTemplate.opsForValue().set("telephone",validateCode);
            result.setData(validateCode);
            result.setFlag(true);
            result.setMessage(MessageConstant.SEND_VALIDATECODE_SUCCESS);
            return result;
        } catch (Exception e) {
            throw new orderException(MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
